<?php
class User_emergency_model extends CI_Model {

	function __construct()
    {
        parent::__construct();
    }
    /**
	 * 获取用户信息
	 * @param int $id
	 */
	public function find_by_id($id) {
		$this->db->where('id', $id);
		return $this->db->get('user_emergency')->row_array();
	}
	
	public function add($data) {
		$this->db->insert("user_emergency", $data);
		return $this->db->insert_id();
	}
	
	/**
	 * 查找申请者
	 * @param int $emergency_id
	 */
	public function find_applier($emergency_id , $limit = null) {
		$sql = " select u.nickname, u.email ,ue.* from user_emergency ue left join users u on u.id=ue.user_id
		 where emergency_id = " . intval($emergency_id);
		if (!empty($limit)) {
			$sql .= " limit " . $limit;
		}
		return $this->db->query($sql)->result_array();
	}
	/**
	 * 是否申请过
	 * @param int $emergency_id
	 * @param int $user_id
	 */
	public function is_applied($emergency_id, $user_id) {
		$sql = " select count(*) as total from user_emergency where user_id=" . intval($user_id) . " and emergency_id="
		. $emergency_id;
		$result = $this->db->query($sql)->row_array();
		return ($result['total'] > 0 ? 1 : 0);
	}
	
	/**
	 * 获取用户报名的story
	 * @param int $user_id
	 * @param int $offset
	 * @param int $limit
	 */
	public function find_applied_stories($user_id,  $offset = 0, $limit = 10) {
		$sql = " select distinct(g.id),g.bonus,g.title,g.created_by,g.created,u.nickname,u.id from emergencies g 
		left join user_emergency ue on g.id=ue.emergency_id
		left join users u on u.id=ue.user_id
		 where ue.user_id=" . $user_id;
		$sql .= " limit " . $offset . ", " . $limit;
		return $this->db->query($sql)->result_array();
	}
	
	/**
	 * 获取用户报名的story
	 * @param int $user_id
	 * @param int $offset
	 * @param int $limit
	 */
	public function get_count_applied_stories($user_id) {
		$sql = " select count(distinct(emergency_id)) as total from  user_emergency  where user_id=" . $user_id;
		$result = $this->db->query($sql)->row_array();
		return $result['total'];
	}
	/**
	 * 更新应征状态
	 * @param int $user_id
	 * @param int $story_id
	 */
	public function update_status($user_id, $story_id) {
		$sql = "update user_emergency set status=1,employ_time='" . date("Y-m-d H:i:s") . "' where user_id=" .
				$user_id . " and emergency_id=" . $story_id;
		return $this->db->query($sql);
	}
	
/**
	 * 查找雇佣者
	 * @param int $emergency_id
	 */
	public function find_employer($emergency_id , $limit = null) {
		$sql = " select u.nickname, u.email ,ue.* from user_emergency ue left join users u on u.id=ue.user_id
		 where ue.status=1 and ue.emergency_id = " . intval($emergency_id);
		if (!empty($limit)) {
			$sql .= " limit " . $limit;
		}
		return $this->db->query($sql)->result_array();
	}
}